<template>
  <div class="rule-setting-container">
    <h2 class="rule-section-title">
      <span style="vertical-align: middle" slot="reference">
        {{$t('performance.reportSetting.title')}}
        <!-- <i class="icon-help iconfont" style="margin-left: 3px"></i> -->
      </span>
      <base-button
        type="primary"
        native-type="submit"
        @event="batchSetting"
        >{{$t('performance.reportSetting.batchSetting')}}</base-button
      >
    </h2>

    <div class="table-wrap">
      <div v-for="(type, index) in themeList" :key="type.reportKey">
        <div class="table-header">
          <div class="table-title">{{ type.reportName }}</div>
          <el-button class="table-fold" type="text" @click="foldTable(index)">{{type.showTable ? $t('common.base.collapse') : $t('common.base.expand')}}</el-button>
        </div>

        <el-table
          v-table-style
          v-show="type.showTable"
          border
          :data="type.themeList"
          v-loading="loading"
          class="rule-table"
          ref="ruleTable"
          :highlight-current-row="false"
          @select-all="allSelectionChange"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55">
          </el-table-column>
          <el-table-column :label="$t('common.base.SN')" type="index" width="55"> </el-table-column>
          <el-table-column prop="reportName" :label="$t('performance.reportSetting.displayName.reportName')">
          </el-table-column>
          <el-table-column prop="dimensionName" :label="$t('performance.reportSetting.displayName.reportDimension')">
          </el-table-column>
          <el-table-column fixed="right" :label="$t('common.base.operation')">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="openUser(scope.row.id, scope.row.reportMold)"
                >{{$t('performance.reportSetting.authSet')}}</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>


		<!-- start 节点负责人选择弹窗 -->
    <base-modal
      class="choose-user-modal"
      :title="nodeCandidateTitle2"
      :show.sync="visible"
      width="640px"
    >
      <config-contact
        ref="configContact"
        :title="nodeCandidateTitle"
        :value="candidates"
        :show-search="false"
        v-if="visible"
      />

      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">{{$t('common.base.cancel')}}</el-button>
        <el-button type="primary" @click="chooseUser">{{$t('common.base.confirm')}}</el-button>
      </div>
    </base-modal>
    <!-- end 节点负责人选择弹窗 -->
  </div>
</template>

<script>
import {
  getReportList,
  saveReportAuthority,
  getReportThemeAuthority 
} from '@src/api/PerformanceApi'
import { grayQrCodeFunction } from '@src/api/productQrcode';

import BaseSelectUser from '@src/component/common/BaseSelectUser'

/* model */
import { BaseSelectUserTypeIdEnum } from '@src/component/common/BaseSelectUser/model'
import { t } from '@src/locales';

export default {
  name: 'report-rloe-setting',
  props: {
    initData: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      themeList: [],
      loading: false,
			visible: false,
      nodeCandidateTitle: t('performance.reportSetting.reportAuth'),
			nodeCandidateTitle2: t('performance.reportSetting.selectReportAuth'),
			candidates: undefined,
      reportId: [],
      reportSelectedList: [],
      isAll: false,
      oneReportId: {},
      superQrCodeGrayFlag: false,
      selectedList: []
    };
  },
  async created() {
    // await this.grayQrCodeFunction();

    this.getThemeList();
  },
  watch: {
    visible(nv,ov){
      if(!nv && !this.isAll) this.oneReportId = {};
    }
  },
  methods: {
    foldTable(index) {
      this.themeList[index].showTable = !this.themeList[index].showTable
    },
		async openUser(id, reportMold) {
      this.isAll = false;
      let authorityData = await this.getThemeAuthority(id, reportMold)//数据回填
      this.candidates = this.buildAuthority(authorityData)
      // const { users, roles, depts} = this.translateDataForCom(authorityData)
      // const options = {
      //   title:`${this.nodeCandidateTitle}选择`,
      //   selectedUsers:users, 
      //   selectedRoles:roles, 
      //   selectedDepartments:depts
      // }
      this.reportId = [id]
      this.oneReportId = {
        reportId: id,
        reportMold
      };
      // this.$fast.select.multi.all(options).then(res=>{
      //   if(res.status == 0){
      //     let params = this.translateDataForHttp(res.data);
      //     this.saveReport({...params})
      //   }
      // })
      
      
      this.openSelectUserDialog()
			// // this.visible = true
		},
    buildAuthority(data) {
      let userType = {
        'USER': 1,//用户
        'TAG': 2,//部门
        'ROLE': 3//角色
      }
      return data.map(item => {
        let { objId, objName, objType, staffId} = item
        return {
          id: objId,
          name: objName,
          type: userType[objType],
          staffId,
        }
      })
    },
    /**
     * @des 从接口转换数据为新组件服务
     */
    translateDataForCom(arr){
      let users = [];
      let roles = [];
      let depts = [];
      let userType = {
        'USER': (item)=>{
          const {objName, id} = item;
          item['displayName'] = objName;
          item['userId'] = id;
          users.push(item)
        },//用户
        'TAG': (item)=>{
          const {objName, objId} = item;
          item['name'] = objName;
          item['id'] = objId;
          depts.push(item)
        },//部门
        'ROLE': (item)=>{
          const {objName, objId} = item;
          item['name'] = objName;
          item['id'] = objId;
          roles.push(item)
        }//角色
      }
      try {
        arr.forEach(item=>{
          const { objType } = item;
          userType[objType] && userType[objType](item)
        })
      } catch (error) {
        console.warn(error, 'error try catch');
      }
      return {
        users, roles, depts
      }
    },
    /**
     * @des 把新组件数据回转为原有接口数据
     */
    translateDataForHttp({users, roles, depts}){
      // 暂不考虑选择数据的顺序
      let arr_ = [];
      users.forEach(item=>{
        const { userId } = item;
        arr_.push({
          objId:userId,
          objType:'USER'
        })
      })
      roles.forEach(item=>{
        const { id } = item;
        arr_.push({
          objId:id,
          objType:'ROLE'
        })
      })
      depts.forEach(item=>{
        const { id } = item;
        arr_.push({
          objId:id,
          objType:'TAG'
        })
      })
      let params = {
				reportAuthorityList: arr_,
        reportList: this.isAll ? this.reportId : [ this.oneReportId ],
        isAll: this.isAll
			}
      return params;
    },
    allSelectionChange(rows) {
      this.reportSelectedList = rows || []
      this.getReportId(rows)
    },
    handleSelectionChange(val) {
      this.reportSelectedList = val || []
      this.getReportId(val)
    },
    getReportId(data) {
      this.reportId = data.map(report => { 
        return {
          reportId: report.id,
          reportMold: report.reportMold
        }
      })
    },
    batchSetting() {//批量配置 
      this.$track.clickStat(this.$track.formatParams('BATCH_CONFIGURATION_PERMISSION'))

      this.candidates = [];
      if (!this.reportSelectedList.length) {
        this.$message({
          message: t('performance.reportSetting.tip.selectData'),
          type: 'warning'
        });
        return
      }

      // 批量配置时重新赋值
      this.isAll = true;
      this.getReportId(this.reportSelectedList)
      // this.visible = true
      
      this.openSelectUserDialog()
		},
		chooseUser() {
			// let checked = this.$refs.configContact.checked
      let checked = this.selectedList
      let params = this.buildParams(checked)

      this.saveReport(params)

      this.visible = false
		},
    buildParams(data) {
      let userType = {
        1: 'USER', // 用户
        2: 'TAG', // 部门
        3: 'ROLE', // 角色
        4: 'ROLE', // 角色
      }

      let userList = data.map(user => {
        let { id, type } = user
        return { objId: id, objType: userType[type] }
      });

			let params = {
				reportAuthorityList: userList,
        reportList: this.isAll ? this.reportId : [ this.oneReportId ],
        isAll: this.isAll
			}
      return params
    },
		saveReport(params) {//保存权限配置
			saveReportAuthority(params)
        .then(res => {
          this.loading = false;

          if (res.code !== 200) {
            this.$message({
              message: res.msg || t('common.base.tip.unknownError2'),
              type: 'warning'
            })
            return
          }
          this.$message({
            message: t('common.base.tip.saveSuccess'),
            type: 'success'
          })

          this.reportId = []
          this.candidates = []
        
          this.themeList.forEach((_, index) => {
            this.$refs["ruleTable"][index].clearSelection()
          })
        })
        .catch(e => console.error('e', e));
		},
    getThemeList() {//获取数据
      this.loading = true
      getReportList()
        .then(res => {
          if (res.code !== 200) {
            this.$message({
              message: res.msg || t('common.base.tip.unknownError2'),
              type: 'warning'
            })
            return
          }
          let data = res.data || []
          this.themeList = data.map(item => {
            item.showTable = true
            return item
          })
        })
        .catch(e => console.error('e', e))
        .finally(() => {
          this.loading = false
        })
    },
    getThemeAuthority(id, reportMold) { // 获取已设置的权限
      try {
        return getReportThemeAuthority(id, reportMold).then(res => res.data || [])
      }catch (error) {
        console.warn('error')
        return []
      }
    },
    /* 超级二维码行为分析灰度 */
    async grayQrCodeFunction(){
        try{
            const res = await grayQrCodeFunction();
            if(res.status !== 0) return;

            this.superQrCodeGrayFlag = res.data.QRCODE_REPORT;
        }catch(err){
            console.log(err);
        }
    },
    // 过滤数据
    filterThemeList(list){
      if(this.superQrCodeGrayFlag) return list;
      return list.filter(x => x.reportKey !== 'SUPERQRCODEANALYSIS');
    },
    openSelectUserDialog() {
      
      const options = {
        title: t('performance.reportSetting.selectReportAuth'),
        showServiceProvider: false,
        selectedAll: this.candidates?.map(item => {
          item.typeId = item.type == 3 ? BaseSelectUserTypeIdEnum.Role : item.type
          return item
        }) || [],
        isTag: true,
        // 是否只显示 服务云 角色，如果是服务云版本的话。
        isOnlyShowBusinessServiceCloudRole: true
      }
      
      BaseSelectUser.props.multi.all(options).then(result => {
        
        const all = result.data.all.map(item => {
          item.type = item.typeId
          item.id = item.id || item.userId
          return item
        })
        
        this.selectedList = all
        
        this.chooseUser()
      })
    }
  }
};
</script>

<style lang="scss">
.rule-setting-container {
  background: #ffffff;
  padding: 10px;

  .rule-section-title {
    display: flex;
    justify-content: space-between;
    line-height: 32px;
    font-size: 16px;
    margin: 0;
  }

  // table
  .rule-table {
    margin-top: 10px;
    th {
      background: #f5f5f5;
      color: $text-color-primary;
      font-weight: normal;
      font-size: 14px;
      line-height: 34px;
      color: #333;
    }
    td {
      font-size: 13px;
    }

    .el-table__body {
      width: 100% !important;
    }
  }
}
</style>
<style lang="scss" scoped>
.table-wrap {
  width: 100%;
  height: 100%;
  padding-top: 20px;
  .table-header {
    display: flex;
    justify-content: space-between;
    .table-title {
      font-size: 16px;
      height: 40px;
      line-height: 40px;
    }
  }
  .rule-table {
    margin-bottom: 20px;
  }
}
</style>
